package com.app.teaware.goods;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.basis.Constants;
import com.app.teaware.bean.GoodsListBean;
import com.app.teaware.bean.GoodsListData;
import com.app.teaware.bean.GoodsWorks;
import com.app.teaware.bean.KWListBean;
import com.app.teaware.bean.LoginBean;
import com.app.teaware.bean.MenuBean;
import com.app.teaware.util.LetterUtil;
import com.app.teaware.util.MyUtils;
import com.app.teaware.util.NumberUtil;
import com.app.teaware.util.UHFUtil;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import my.ActivityTool;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/***
 * 添加入库资料
 * **/
public class AddGoodsInfoActivity extends BasisActivity {

    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    @BindView(R.id.edit_code)
    EditText edit_code;
    @BindView(R.id.edit_name)
    EditText edit_name;
    @BindView(R.id.edit_specs)
    EditText edit_specs;
    @BindView(R.id.edit_price)
    EditText edit_price;
    @BindView(R.id.edit_num)
    EditText edit_num;
    @BindView(R.id.edit_weight)
    EditText edit_weight;
    @BindView(R.id.edit_qrcode)
    EditText edit_qrcode;
    @BindView(R.id.text_kw)
    TextView text_kw;

    String tid;
    String cid;     //工艺 ID
    String gid;

    KWListBean kwListBean;

    ArrayList<GoodsWorks> worksList = new ArrayList<>();
    GoodsWorks works;

    String wbx;  //
    String dbx;  //

    public  static void toDetail(Activity context, String tid, String cid,int requst){
        Bundle extras = new Bundle();
        extras.putString("tid",tid);
        extras.putString("cid",cid);
        ActivityTool.skipActivityForResult(context,AddGoodsInfoActivity.class,extras,requst);
    }


    public  static void toEdit(Activity context, String tid, String cid,GoodsWorks works, int requst){
        Bundle extras = new Bundle();
        extras.putString("tid",tid);
        extras.putString("cid",cid);
        extras.putSerializable("works",works);
        ActivityTool.skipActivityForResult(context,AddGoodsInfoActivity.class,extras,requst);
    }


    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        setContentView(R.layout.add_goods_info_activity);
        setTitle("添加入库资料");
        setTitleLeftButton(null);

        setTitleLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(worksList != null && worksList.size()>0){
                    Intent data = new Intent();
                    data.putExtra("list", worksList);
                    setResult(Constants.SCANDATASULT,data);
                }
                finish();
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);
        tid= getIntent().getStringExtra("tid");
        cid= getIntent().getStringExtra("cid");
        works = (GoodsWorks) getIntent().getSerializableExtra("works");
        registerResultReceiver();
        UHFUtil.allTriggerModeOpen();
        intSpinner();
    }


    @OnClick(R.id.view_kw)
    void kwBtn() {
        if(kwListBean.getAllNames() == null) return;
        new QMUIDialog.MenuDialogBuilder(mContext)
                .setSkinManager(QMUISkinManager.defaultInstance(mContext))
                .addItems(kwListBean.getAllNames(), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        showToast("你选择了 " + types[which]);
                        text_kw.setText(kwListBean.getAllNames()[which]);
                        dialog.dismiss();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }



    void intSpinner(){
        showLoading();
        MyParams params = new MyParams();
        params.put("aid", LoginBean.getInstance().getAcode());
        MyHttpUtils.get(Constants.URL_WARE_SELECT_ALL, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if(isFinishing()) return;
                        kwListBean = (KWListBean) result;
//                        String[] names = kwListBean.getAllNames();
//                        if(names!= null && names.length>0){
//                            text_kw.setText(names[0]);
//                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        hideLoading();
                        if(works == null){
                            works = new GoodsWorks();
                        }else {
                            initWorks();
                        }
                    }
                },
                0, KWListBean.class);

    }

    void initWorks(){
        edit_code.setText(works.getGno());
        edit_name.setText(works.getGna());
        edit_specs.setText(works.getGsp());
        edit_price.setText(works.getGun());
        edit_num.setText(""+works.getGnu());
        edit_weight.setText(""+works.getGwt());
        gid = works.getGid();
        wbx = works.getWbx();
        dbx = works.getDbx();
        text_kw.setText(works.getWms());
        edit_qrcode.setText(works.getRfid());
    }


    @OnClick({R.id.btn_code,R.id.btn_scan,R.id.btn_specs,R.id.btn_price})
    void btnOnclick(){
        if(TextUtils.isEmpty(tid)){
            showToast("单号不能为空");
            return;
        }
        ActivityTool.skipActivityForResult(mContext,GoodsDataActivity.class,Constants.GOODSDATARESULT);
    }


    private boolean httpIsFinish = true;
    private void getGoodsDataByEpcId(){
        if(!httpIsFinish) return;
        httpIsFinish = false;
        if(TextUtils.isEmpty(edit_qrcode.getText().toString().trim())) return;
        if(TextUtils.isEmpty(cid)) return;

        showLoading();
        MyParams params = new MyParams();
        params.put("aid", LoginBean.getInstance().getAcode());
//        params.put("cid", cid);
        params.put("rfid",edit_qrcode.getText().toString().trim());
//        MenuBean menuBean = LoginBean.getInstance().getMenuBeanByMna(MyUtils.getHomeSelectName());
//        params.put("id",menuBean.getId());
        MyHttpUtils.get(Constants.URL_WORK_SELECT_BY_RFID, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if(isFinishing()) return;
                        GoodsListBean listBean = (GoodsListBean) result;
                        if(listBean != null && listBean.getList().size()>0){
                            GoodsListData  data = listBean.getList().get(0);
                            edit_code.setText(data.getGno());
                            edit_name.setText(data.getGna());
                            edit_specs.setText(data.getGsp());
                            edit_price.setText(data.getGun());
                            edit_num.setText(data.getNum());
                            edit_weight.setText(data.getWgt());
                            if(data.getNum().equals("0.0") ||TextUtils.isEmpty(data.getNum()) && TextUtils.isEmpty(data.getWgt()) || data.getWgt().equals("0.0")){
                                edit_num.setEnabled(true);
                                edit_weight.setEnabled(true);
                            }else {
                                edit_num.setEnabled(false);
                                edit_weight.setEnabled(false);
                            }
                            gid = data.getGid();
                            wbx = data.getWbx();
                            dbx = data.getDbx();
                            text_kw.setText(data.getLoc1());
                        }
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        httpIsFinish = true;
                        hideLoading();
                    }
                },
                0, GoodsListBean.class);

    }



    GoodsListData resultGoodsData;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Constants.GOODSDATARESULT){
            resultGoodsData = (GoodsListData) data.getSerializableExtra("data");
            if(resultGoodsData != null){
                edit_code.setText(resultGoodsData.getGno());
                edit_name.setText(resultGoodsData.getGna());
                edit_specs.setText(resultGoodsData.getGsp());
                edit_price.setText(resultGoodsData.getGun());
                gid = resultGoodsData.getGid();
            }
        }
    }


    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if(!Constants.ACTION_UHF_RESULT_SEND.equals(action))
                return ;
            Parcelable[] tagInfos =  intent.getParcelableArrayExtra(Constants.EXTRA_TAG_INFO);
            String qrcode = UHFUtil.getEPCId(tagInfos).trim();
            if(TextUtils.isEmpty(qrcode)) return;
            String startStr = qrcode.substring(0,1);
            if(NumberUtil.isNumeric(startStr)){
                text_kw.setText(qrcode);
            }
            if(LetterUtil.isLetter(startStr)){
                edit_qrcode.setText(qrcode);
                getGoodsDataByEpcId();
            }
        }//end onReceiver
    };




    @Override
    protected void onPause() {
        super.onPause();
        unRegisterResultReceiver();
        UHFUtil.setMinPowerDB();
        UHFUtil.allTriggerModeOpen();
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerResultReceiver();
    }

    private void registerResultReceiver() {
        try {
            IntentFilter iFilter = new IntentFilter(Constants.ACTION_UHF_RESULT_SEND);
            mContext.registerReceiver(mResultReceiver, iFilter);
        } catch (Exception e) {
        }

    }

    private void unRegisterResultReceiver() {
        try {
            mContext.unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
        }

    }


    private boolean isOk = false;
    @OnClick(R.id.btn_add)
    void btnAdd(){
        isOk = false;
        if(TextUtils.isEmpty(edit_code.getText().toString())){
            showToast("单号不能为空");
            return;
        }
        if(TextUtils.isEmpty(edit_num.getText().toString())){
            showToast("数量不能为空");
            return;
        }
        if(Double.valueOf(edit_num.getText().toString()) == 0){
            showToast("数量不为0");
            return;
        }
        if(TextUtils.isEmpty(edit_weight.getText().toString())){
            showToast("重量不能为空");
            return;
        }

        if(Double.valueOf(edit_weight.getText().toString()) == 0){
            showToast("重量不为0");
            return;
        }
        if(TextUtils.isEmpty(text_kw.getText().toString())){
            showToast("库位不能为空");
            return;
        }
        if(TextUtils.isEmpty(edit_qrcode.getText().toString())){
            showToast("箱码不能为空");
            return;
        }
        works.setBfs(MyUtils.getHomeSelectId());
        works.setGna(edit_name.getText().toString());
        works.setGno(edit_code.getText().toString());
        works.setGun(edit_price.getText().toString());
        works.setGsp(edit_specs.getText().toString());
        works.setGnu(edit_num.getText().toString());
        works.setGwt(edit_weight.getText().toString());
        works.setWms(text_kw.getText().toString());
        works.setRfid(edit_qrcode.getText().toString().trim());
        works.setGid(gid);
        works.setWbx(wbx);
        works.setDbx(dbx);
        worksList.add(works);


        works = new GoodsWorks();
        edit_code.getText().clear();
        edit_name.getText().clear();
        edit_specs.getText().clear();
        edit_price.getText().clear();
//        edit_num.getText().clear();
        edit_weight.getText().clear();
        edit_qrcode.getText().clear();
        text_kw.setText("");
        isOk = true;
    }


    @OnClick(R.id.btn_submit)
    void btnSubmit(){
        btnAdd();
        if(isOk){
            Intent data = new Intent();
            data.putExtra("list", worksList);
            setResult(Constants.SCANDATASULT,data);
            finish();
        }
    }

}
